/* eslint-disable react/jsx-key */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useRef, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { Image, Switch, Button, Modal, message, Popconfirm, Tooltip } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { area, user, classify } from '@/services/basic';
import { connect } from 'umi';
import { PlusOutlined, TagFilled } from '@ant-design/icons';
import { doFetch, getFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import moment from 'moment';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = {
  feedback_describe: {
    value: null,
    type: 'textarea',
    title: '任务描述',
    name: ['feedback_describe'],
    required: true,
    col: {
      span: 24,
    },
  },
  is_completed: {
    value: null,
    type: 'radio',
    title: '是否完成',
    name: ['is_completed'],
    required: true,
    options: [
      {
        label: '完成',
        value: true,
      },
      {
        label: '未完成',
        value: false,
      },
    ],
    col: {
      span: 24,
    },
  },
};

const obj = {
    customer_name: '联系人',
    classify_name: '公司类型',
    receive_order_user_name: '接单人',
    customer_phone: '联系人手机号',
    account_user_name: '记账会计',
    finance_mainer_name: '会计主管',
    unit_price: '月收费',
  },
  objs = {
    customer_name: { show: false },
    classify_name: { show: false },
    receive_order_user_name: { show: false },
    customer_phone: { show: false },
    account_user_name: { show: false },
    finance_mainer_name: { show: false },
    unit_price: { show: false },
  };

function ToDaily(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [type, ctype] = useState('1'),
    [iftype, ciftype] = useState({});

  let actionRef = useRef(),
    ChildRef = null;

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const daily = (content) => ({
      company_id: {
        value: null,
        type: 'checktable',
        title: '代账公司',
        name: ['company_id'],
        columns: [
          {
            title: '业务编号',
            dataIndex: 'code',
            key: 'code',
          },
          {
            title: '公司名称',
            width: 260,
            dataIndex: 'name',
            key: 'name',
            copyable: true,
          },
          {
            title: '月收费',
            dataIndex: 'unit_price',
            key: 'unit_price',
            search: false,
          },
          {
            title: '公司法人',
            dataIndex: 'legal_person',
            key: 'legal_person',
            search: false,
          },
          {
            title: '联系人',
            dataIndex: 'customer_name',
            key: 'customer_name',
            ellipsis: true,
            search: false,
          },
          {
            title: '联系人手机号',
            width: 120,
            dataIndex: 'customer_phone',
            key: 'customer_phone',
            search: false,
            render: (_, row) => (
              <Tooltip title={row.customer_phone}>
                <a href={`tel:${row.customer_phone}`} className="oneline">
                  {row.customer_phone}
                </a>
              </Tooltip>
            ),
          },
          {
            title: '区域名称',
            dataIndex: 'area_name',
            key: 'area_name',
            search: false,
          },
          {
            title: '记账会计',
            dataIndex: 'account_user_name',
            key: 'account_user_name',
          },
          {
            title: '公司类型',
            dataIndex: 'classify_name',
            key: 'classify_name',
            search: false,
          },
        ],
        rowKey: 'id',
        rowName: 'name',
        required: true,
        path: '/wbn-api/company',
        tabletype: 'radio',
        col: { span: 24 },
      },
      area_id: {
        value: null,
        type: 'select',
        title: '区域',
        name: ['area_id'],
        required: true,
        options: {
          database: area,
          params: { is_all: 1 },
        },
      },
      work_type_id: {
        value: null,
        type: 'select',
        title: '办事类型',
        name: ['work_type_id'],
        required: true,
        options: {
          database: (params) => getFetch({ url: '/wbn-api/work_type', params }),
          params: { is_all: 1 },
        },
      },
      work_type_level: {
        value: null,
        type: 'select',
        title: '重要程度',
        name: ['work_type_level'],
        required: true,
        formart: ['type', 'name'],
        options: {
          database: (params) => getFetch({ url: '/wbn-api/work_level', params }),
          params: { is_all: 1 },
        },
      },
      limit_day: {
        value: null,
        type: 'inputnumber',
        title: '办理期限（天）',
        name: ['limit_day'],
        required: true,
      },
      task_describe: {
        value: content,
        type: 'textarea',
        title: '任务描述',
        name: ['task_describe'],
        required: false,
        col: {
          span: 24,
        },
      },
      user_id: {
        value: null,
        type: 'select',
        title: '经办人',
        name: ['user_id'],
        required: true,
        options: {
          database: user,
          params: { is_all: 1, enable: true },
        },
        col: {
          span: 24,
        },
      },
    }),
    paydaily = (content) => ({
      company_id: {
        value: null,
        type: 'checktable',
        title: '代账公司',
        name: ['company_id'],
        columns: [
          {
            title: '业务编号',
            dataIndex: 'code',
            key: 'code',
          },
          {
            title: '公司名称',
            width: 260,
            dataIndex: 'name',
            key: 'name',
            copyable: true,
          },
          {
            title: '月收费',
            dataIndex: 'unit_price',
            key: 'unit_price',
            search: false,
          },
          {
            title: '公司法人',
            dataIndex: 'legal_person',
            key: 'legal_person',
            search: false,
          },
          {
            title: '联系人',
            dataIndex: 'customer_name',
            key: 'customer_name',
            ellipsis: true,
            search: false,
          },
          {
            title: '联系人手机号',
            width: 120,
            dataIndex: 'customer_phone',
            key: 'customer_phone',
            search: false,
            render: (_, row) => (
              <Tooltip title={row.customer_phone}>
                <a href={`tel:${row.customer_phone}`} className="oneline">
                  {row.customer_phone}
                </a>
              </Tooltip>
            ),
          },
          {
            title: '区域名称',
            dataIndex: 'area_name',
            key: 'area_name',
            search: false,
          },
          {
            title: '记账会计',
            dataIndex: 'account_user_name',
            key: 'account_user_name',
          },
          {
            title: '公司类型',
            dataIndex: 'classify_name',
            key: 'classify_name',
            search: false,
          },
        ],
        rowKey: 'id',
        rowName: 'name',
        required: true,
        path: '/wbn-api/company',
        tabletype: 'radio',
        col: { span: 24 },
      },
      area_id: {
        value: null,
        type: 'select',
        title: '区域',
        name: ['area_id'],
        required: true,
        options: {
          database: area,
          params: { is_all: 1 },
        },
      },
      payment_work_type_id: {
        value: null,
        type: 'select',
        title: '收款类型',
        name: ['payment_work_type_id'],
        required: true,
        options: {
          database: (params) => getFetch({ url: '/wbn-api/payment_work_type', params }),
          params: { is_all: 1 },
        },
      },
      limit_day: {
        value: null,
        type: 'inputnumber',
        title: '办理期限（天）',
        name: ['limit_day'],
        required: true,
      },
      payment_nature: {
        value: null,
        type: 'select',
        title: '收款性质',
        name: ['payment_nature'],
        required: true,
        options: [
          {
            value: 'normal', //normal 正常 delay 逾期
            label: '正常',
          },
          {
            value: 'delay',
            label: '逾期',
          },
        ],
      },
      task_describe: {
        value: content,
        type: 'textarea',
        title: '任务描述',
        name: ['task_describe'],
        required: false,
        col: {
          span: 24,
        },
      },
      user_id: {
        value: null,
        type: 'select',
        title: '经办人',
        name: ['user_id'],
        required: true,
        options: {
          database: user,
          params: { is_all: 1, enable: true },
        },
        col: {
          span: 24,
        },
      },
    });

  const { data } = useRequest(async () => {
    let unnum = await getFetch({ url: '/wbn-api/daily_work', params: { is_todo: true } });
    let unnums = await getFetch({ url: '/wbn-api/payment_work', params: { is_todo: true } });
    let result = await getFetch({ url: '/wbn-api/work_level', params: { is_all: 1 } });
    return {
      unnum: unnum?.data?.total,
      unnums: unnums?.data?.total,
      workTypeLevel: result?.data,
    };
  });

  const tabList = [
    {
      key: '1',
      tab: `日常事项(待处理${data?.unnum ?? '-'})`,
    },
    {
      key: '2',
      tab: `收款事项(待处理${data?.unnums ?? '-'})`,
    },
  ];

  const columns = useMemo(() => {
    const arrs = Object.keys(obj)?.map((it) => {
      return {
        title: obj[it],
        dataIndex: it,
        key: it,
        search: false,
      };
    });
    if (type === '1') {
      return [
        {
          title: '公司编号',
          dataIndex: 'company_code',
          key: 'company_code',
        },
        {
          title: '公司名称',
          dataIndex: 'company_name',
          key: 'company_name',
          render: (_, row) => (
            <CompanyName
              row={{ ...row, name: row?.company_name ?? row.name, id: row?.company_id ?? row.id }}
              reload={reload}
            />
          ),
        },
        {
          title: '区域',
          dataIndex: 'area_name',
          key: 'area_name',
          valueType: 'select',
          options: {
            database: area,
            params: {
              is_all: 1,
            },
          },
        },
        {
          title: '办事类型',
          dataIndex: 'work_type_name',
          key: 'work_type_id',
          search: false,
          // valueType: 'select',
          // options: {
          //   database: (params) => getFetch({ url: '/wbn-api/work_type', params }),
          //   params: { is_all: 1 },
          // },
        },
        {
          title: '重要程度',
          dataIndex: 'work_type_level',
          key: 'work_type_level',
          search: false,
          render: (text, row) => {
            let res = data?.workTypeLevel?.filter?.((it) => it?.type === row?.work_type_level);

            return res?.[0]?.name ?? '-';
          },
        },
        {
          title: '办理期限（天）',
          dataIndex: 'limit_day',
          key: 'limit_day',
          search: false,
        },
        {
          title: '任务描述',
          dataIndex: 'task_describe',
          key: 'task_describe',
          search: false,
        },
        {
          title: '经办人',
          dataIndex: 'user_name',
          key: 'user_name',
        },
        {
          title: '创建时间-开始',
          dataIndex: 'start_date',
          key: 'start_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间-结束',
          dataIndex: 'end_date',
          key: 'end_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at',
          search: false,
          render: (_text, row) => {
            const text = row.created_at;
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-';
          },
        },
        {
          title: '剩余天数',
          dataIndex: 'remaining_day',
          key: 'remaining_day',
        },
        {
          title: '创建人',
          dataIndex: 'creator_name',
          key: 'creator_name',
          search: false,
        },
        {
          title: '反馈人',
          dataIndex: 'feedback_user_name',
          key: 'feedback_user_name',
          search: false,
        },
        {
          title: '反馈时间',
          dataIndex: 'feedback_time',
          key: 'feedback_time',
          search: false,
          render: (text, record) => {
            return record?.feedback_time
              ? moment(record?.feedback_time).format('YYYY-MM-DD HH:mm:ss')
              : '-';
          },
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          valueType: 'select',
          options: [
            {
              value: 'normal',
              label: '进行中',
            },
            {
              value: 'delay',
              label: '延期',
            },
            {
              value: 'un_completed',
              label: '未办结',
            },
            {
              value: 'completed',
              label: '已完成',
            },
          ],
          render: (text, row) => {
            const cofs = {
              normal: '进行中',
              delay: '延期',
              un_completed: '未完成',
              completed: '已完成',
            };
            return (
              <div className="centerl" style={{ gap: 12 }}>
                {cofs[row?.status]}
                {row?.feedback_describe && ['un_completed', 'completed']?.includes(row?.status) && (
                  <TagFilled
                    style={{ color: '#1890ff' }}
                    onClick={() => {
                      Modal.info({
                        title: '反馈信息',
                        content: row?.feedback_describe,
                      });
                    }}
                  />
                )}
              </div>
            );
          },
        },
        ...arrs,
        {
          title: '操作',
          valueType: 'option',
          width: 180,
          render: (text, record, _, action) => [
            record.status === 'normal' && (
              <a
                onClick={() => {
                  cvs(true);
                  cf((fields) => {
                    for (let i in defaultFields) {
                      defaultFields[i].value = null;
                    }
                    return { ...defaultFields };
                  });
                  ciftype({
                    val: 'reply',
                    title: '反馈',
                    id: record?.id,
                  });
                }}
              >
                反馈
              </a>
            ),
          ],
        },
      ];
    } else {
      return [
        {
          title: '公司编号',
          dataIndex: 'company_code',
          key: 'company_code',
        },
        {
          title: '公司名称',
          dataIndex: 'company_name',
          key: 'company_name',
          render: (_, row) => (
            <CompanyName
              row={{ ...row, name: row?.company_name ?? row.name, id: row?.company_id ?? row.id }}
              reload={reload}
            />
          ),
        },
        {
          title: '区域',
          dataIndex: 'area_name',
          key: 'area_name',
          valueType: 'select',
          options: {
            database: area,
            params: {
              is_all: 1,
            },
          },
        },
        {
          title: '收款类型',
          dataIndex: 'payment_work_type_name',
          key: 'payment_work_type_name',
          search: false,

          // valueType: 'select',
          // options: {
          //   database: (params) => getFetch({ url: '/wbn-api/payment_work_type', params }),
          //   params: { is_all: 1 },
          // },
        },
        {
          title: '收款性质',
          dataIndex: 'payment_nature',
          key: 'payment_nature',
          search: false,
          render: (text, row) => {
            let cofs = {
              normal: '进行中',
              delay: '逾期',
            };
            return cofs[row?.payment_nature] ?? '-';
          },
        },
        {
          title: '办理期限（天）',
          dataIndex: 'limit_day',
          key: 'limit_day',
          search: false,
        },
        {
          title: '任务描述',
          dataIndex: 'task_describe',
          key: 'task_describe',
          search: false,
        },
        {
          title: '经办人',
          dataIndex: 'user_name',
          key: 'user_name',
        },
        {
          title: '创建时间-开始',
          dataIndex: 'start_date',
          key: 'start_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间-结束',
          dataIndex: 'end_date',
          key: 'end_date',
          hideInTable: true,
          valueType: 'date',
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          key: 'created_at',
          search: false,
          render: (_text, row) => {
            const text = row.created_at;
            return text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-';
          },
        },
        {
          title: '剩余天数',
          dataIndex: 'remaining_day',
          key: 'remaining_day',
        },
        {
          title: '创建人',
          dataIndex: 'creator_name',
          key: 'creator_name',
          search: false,
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          valueType: 'select',
          options: [
            {
              value: 'normal',
              label: '进行中',
            },
            {
              value: 'delay',
              label: '延期',
            },
            {
              value: 'un_completed',
              label: '未办结',
            },
            {
              value: 'completed',
              label: '已完成',
            },
          ],
          render: (text, row) => {
            const cofs = {
              normal: '进行中',
              delay: '延期',
              un_completed: '未完成',
              completed: '已完成',
            };
            return (
              <div className="centerl" style={{ gap: 12 }}>
                {cofs[row?.status]}
                {row?.feedback_describe && ['un_completed', 'completed']?.includes(row?.status) && (
                  <TagFilled
                    style={{ color: '#1890ff' }}
                    onClick={() => {
                      Modal.info({
                        title: '反馈信息',
                        content: row?.feedback_describe,
                      });
                    }}
                  />
                )}
              </div>
            );
          },
        },
        ...arrs,
        {
          title: '操作',
          valueType: 'option',
          width: 100,
          render: (text, record, _) => [
            record.status === 'normal' ? (
              <a
                onClick={() => {
                  cvs(true);
                  cf((fields) => {
                    for (let i in defaultFields) {
                      defaultFields[i].value = null;
                    }
                    return { ...defaultFields };
                  });
                  ciftype({
                    val: 'replys',
                    title: '反馈',
                    id: record?.id,
                  });
                }}
              >
                反馈
              </a>
            ) : (
              '-'
            ),
          ],
        },
      ];
    }
  }, [type, data]);

  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      message.destroy();
      if (result.code == 0) {
        message.success('操作成功');
        reload();
        cvs(false);
      } else {
        message.error(result.message);
      }
    },
  });

  let saveData = (values) => {
    if (iftype.val === 'reply') {
      run({
        url: '/wbn-api/daily_work/handle_feedback',
        params: { ...values, id: iftype.id },
        method: 'PUT',
      });
    } else if (iftype.val === 'replys') {
      run({
        url: '/wbn-api/payment_work/handle_feedback',
        params: { ...values, id: iftype.id },
        method: 'PUT',
      });
    } else if (iftype.val === 'reedit') {
      run({
        url: '/wbn-api/daily_work/' + iftype.id,
        params: { ...values, company_id: iftype.item.company_id },
        method: 'PUT',
      });
    } else if (iftype.val === 'reedits') {
      run({
        url: '/wbn-api/payment_work/' + iftype.id,
        params: { ...values, company_id: iftype.item.company_id },
        method: 'PUT',
      });
    } else if (iftype.val === 'add') {
      run({
        url: '/wbn-api/daily_work',
        params: { ...values, company_id: values.company_id[0] },
      });
    } else if (iftype.val === 'payadd') {
      run({
        url: '/wbn-api/payment_work',
        params: { ...values, company_id: values.company_id[0] },
      });
    }
  };
  const [columnsStateMap, setColumnsStateMap] = useState(objs);

  let extrarender = [
    <div
      className="action"
      title="新增"
      onClick={() => {
        cvs(true);
        if (type === '1') {
          cf(() => {
            let fields = daily(null);
            for (let i in fields) {
              fields[i].value = null;
            }
            return { ...fields };
          });
        } else {
          cf(() => {
            let fields = paydaily(null);
            for (let i in fields) {
              fields[i].value = null;
            }
            return { ...fields };
          });
        }

        ciftype({
          val: type === '1' ? 'add' : 'payadd',
          title: '新增待办',
        });
      }}
    >
      <PlusOutlined />
    </div>,
  ];

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path={type === '1' ? '/wbn-api/daily_work' : '/wbn-api/payment_work'}
        tabList={tabList}
        extraparams={{
          is_todo: true,
        }}
        onTabChange={(key) => {
          ctype(key);
        }}
        columnsStateMap={columnsStateMap}
        setColumnsStateMap={setColumnsStateMap}
        // withCard={false}
        // cardtitle = "name" //卡片标题
        // cardavatar = "img_url" //卡片头像
      />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={iftype?.val?.includes('add') ? 1366 : 600}
        destroyOnClose={true}
      >
        <InitForm
          fields={fields}
          submitData={(values) => {
            saveData(values);
          }}
          onChange={(changedValues, allValues) => {
            //联动操作
          }}
          submitting={props.loading.effects['basic/addpayment'] || !vs}
        />
      </Modal>
    </div>
  );
}

export default connect(({ basic, loading }) => ({
  basic,
  loading,
}))(ToDaily);
